<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" :closable="false" type="warning"></el-alert>
      <el-row class="fenlei">
        <el-col>
          <span>选择商品分类：</span>
          <!-- options数据源,props是级联选择框的配置对象,v-model是props配置对象里面value组成的数组 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域，v-model对应的就是el-tab-pane的name属性 -->
      <el-tabs v-model="tabActiveName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isDisabled" @click="addDialogVisible = true">添加参数</el-button>
          <!-- 渲染动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开那个效果 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable @close="handleDeleteTag(i,scope.row)" v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <!-- 通过作用域插槽 -->
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isDisabled" @click="addDialogVisible = true">添加属性</el-button>
          <!-- 渲染静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <!-- 通过作用域插槽 -->
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 点击添加参数弹出对话框,他的意思是动态参数和静态属性公用一个对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addDialogClose"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addCateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClose"
    >
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editCateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      cateProps: {
        // 选中的值
        value: 'cat_id',
        // 看到的值
        label: 'cat_name',
        // 父子嵌套的关系
        children: 'children',
        expandTrigger: 'hover'
      },
      // 级联选择框双向绑定到的数组
      selectedCateKeys: [],
      tabActiveName: 'many',
      manyTableData: [],
      onlyTableData: [],
      // 添加参数的对话框显示与隐藏
      addDialogVisible: false,
      // 添加参数的表单
      addCateForm: {
        attr_name: ''
      },
      // 添加参数表单的验证规则
      addCateFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 修改对话框的显示与隐藏
      editDialogVisible: false,
      // 修改对话框的表单
      editCateForm: {},
      // 修改表单的验证规则
      editCateFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 点击tag上面的删除按钮
    handleDeleteTag(i,row){
      row.attr_vals.splice(i,1)
      console.log(row.attr_vals);
      this.saveAttr(row)
    },
    // 保存attr_vals里面的数据
    async saveAttr(row){
      const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if(res.meta.status !== 200){
        this.$message.error('修改参数项失败')
      }
      this.$message.success('修改参数项成功')
    },
    // 监听tag的数据变化
    handleInputConfirm(row){
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false;
        row.inputValue = '';
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false;
      row.inputValue = '';
      // 如果没有return，说明数据有效可以做后续处理
      this.saveAttr(row)
      // row.attr_vals.push(row.inputValue.trim())
      // row.inputVisible = false;
      // row.inputValue = '';
      // const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
      //   attr_name:row.attr_name,
      //   attr_sel:row.attr_sel,
      //   attr_vals: row.attr_vals.join(' ')
      // })
      // if(res.meta.status !== 200){
      //   this.$message.error('修改参数项失败')
      // }
      // this.$message.success('修改参数项成功')
    },
    showInput(row){
      row.inputVisible = true;
      // 他们说一开始文本输入框没渲染，直接获取得不到元素
      // 需要用$nextTick，页面元素全部渲染完毕调用的函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除参数操作
    async removeParams(attr_id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(confirmResult);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除操作错误')
      }
      this.getParamsData()
      this.$message.success('删除成功')
    },
    // 点击修改的操作
    editParams() {
      // 对表单进行预校验
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('表单预校验失败')
        }
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editCateForm.attr_id}`,
          {
            attr_name: this.editCateForm.attr_name,
            attr_sel: this.tabActiveName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('编辑参数提交失败')
        }
        this.editDialogVisible = false
        this.getParamsData()
        this.$message.success('编辑成功')
      })
    },
    // 点击编辑按钮
    async showEditDialog(attr_id) {
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.tabActiveName } }
      )
      if (res.meta.status !== 200) {
        return this.$http.error('通过id查询参数失败')
      }
      this.editCateForm = res.data
      // attr_id也存里面了
      // console.log(this.editCateForm,'hhh哈哈');

      this.editDialogVisible = true
    },
    // 修改对话框关闭的操作
    editDialogClose() {
      this.$refs.editCateFormRef.resetFields()
    },
    // 添加动态参数和静态属性的函数
    addParams() {
      // 添加之前对表单进行预校验
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('表单预校验失败')
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addCateForm.attr_name,
            attr_sel: this.tabActiveName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        // 关闭表单
        this.addDialogVisible = false
        // 刷新数据
        this.getParamsData()
        // 提示添加成功
        this.$message.success('添加参数成功')
      })
    },
    // 关闭对话框时需要重置表单
    addDialogClose() {
      this.$refs.addCateFormRef.resetFields()
    },
    // 获取分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败')
      }
      this.cateList = res.data
      // console.log(this.cateList)
    },
    // 级联选择框值的监听
    handleChange() {
      this.getParamsData()
    },
    // 单弄个函数给级联选择器和tab切换用,获取参数的列表数据
    async getParamsData() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return 
      }
      // 此时打印的必然是三级分类
      // console.log(this.selectedCateKeys)
      // console.log(this.tabActiveName);

      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.tabActiveName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 在这先处理一下展开项expand里面的数据
      res.data.forEach(element => {
        if (element.attr_vals !== '') {
          element.attr_vals = element.attr_vals.split(' ')
        }else{
          element.attr_vals = []
        }
        // 添加tag的显示与隐藏
        element.inputVisible=false;
        // 添加tag的数据双向绑定
        element.inputValue='';
      })
      // 虽然获取了数据，但是分不清是动态参数的数据还是静态属性的数据，这样不方便存储
      if (this.tabActiveName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
      console.log(res.data)
    },
    // tab页签点击监听
    handleTabClick(tab, event) {
      this.getParamsData()
      console.log(this.tabActiveName)
    }
  },
  // 定义一个计算属性
  computed: {
    // 用来禁用按钮
    isDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 用来计算分类id
    cateId() {
      if (this.selectedCateKeys.length !== 3) {
        return null
      }
      // 返回数组最后一位也是第三位
      return this.selectedCateKeys[2]
    },
    // 搞一个计算属性来判断点击添加参数对话框的标题是什么
    titleText() {
      if (this.tabActiveName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.fenlei {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag{
  width: 120px;
}
</style>